package com.xm.concurrent.base;

import com.xm.concurrent.base.util.SleepUtils;

import java.util.concurrent.TimeUnit;

/**
 * 4.3 线程状态
 *
 * @author xiaoming
 * @date 2021-05-18 23:33
 */
public class ThreadState {
    public static void main(String[] args) {
        new Thread(new TimeWaiting(), "TimeWaitingThread").start();
        new Thread(new Waiting(), "WaitingThread").start();
        /// 使用两个 Blocked 线程,一个获取锁成功,一个被阻塞
        new Thread(new Blocked(), "BlockedThread-1").start();
        new Thread(new Blocked(), "BlockedThread-2").start();
/*
jstack pid  查看结果

// BlockedThread-2线程阻塞在获取Blocked.class示例的锁上

"BlockedThread-2" #14 prio=5 os_prio=0 tid=0x000000001d555000 nid=0x3d50 waiting for monitor entry [0x000000001e40f000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at com.xm.concurrent.base.ThreadState$Blocked.run(ThreadState.java:55)
        - waiting to lock <0x000000076b42a4b8> (a java.lang.Class for com.xm.concurrent.base.ThreadState$Blocked)
        at java.lang.Thread.run(Thread.java:748)

// BlockedThread-1线程获取到了Blocked.class的锁

"BlockedThread-1" #13 prio=5 os_prio=0 tid=0x000000001d552800 nid=0x4998 waiting on condition [0x000000001e30e000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)

// WaitingThread线程在Waiting实例上等待

"WaitingThread" #12 prio=5 os_prio=0 tid=0x000000001d8f6000 nid=0x12e0 in Object.wait() [0x000000001e56e000]
   java.lang.Thread.State: WAITING (on object monitor)

// TimeWaitingThread线程处于超时等待

"TimeWaitingThread" #11 prio=5 os_prio=0 tid=0x000000001d8f4000 nid=0x37f0 waiting on condition [0x000000001e46e000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
 */
    }

    // 不断睡眠线程
    static class TimeWaiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                SleepUtils.second(100);
            }

        }
    }

    // 实例等待
    static class Waiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (Waiting.class) {
                    try {
                        Waiting.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    // 实例上锁后, 不释放锁
    static class Blocked implements Runnable{

        @Override
        public void run() {
            synchronized (Blocked.class) {
                SleepUtils.second(100);
            }
        }
    }

}

